package org.smart4j.framework.helper;

import org.smart4j.framework.annotation.Action;
import org.smart4j.framework.bean.Handler;
import org.smart4j.framework.bean.Request;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2016/9/20.
 */
public class ControllerHelper {
    private static final Map<Request,Handler> ACTION_MAP = new HashMap<Request, Handler>();

    static {
        System.out.println("加载 ControllerHelper ");
        // 获取所有controller
        Set<Class<?>> controllerClassSet = ClassHelper.getControllerClassSet();
        if(controllerClassSet != null){
            for(Class<?> controllerClass : controllerClassSet){
                // controller 中所有的方法
                Method[] methods = controllerClass.getDeclaredMethods();
                if(methods != null){
                    for(Method method : methods){
                        // 带有action注解的方法
                        if(method.isAnnotationPresent(Action.class)){
                            // 从action中获取URL映射规则
                            Action action = method.getAnnotation(Action.class);
                            String mapping = action.value();
                            System.out.println("mapping > " + mapping);
                            if(mapping.matches("\\w+:/\\w*")){
                                String[]array = mapping.split(":");
                                if(array != null && array.length == 2){
                                    // 获取方法与请求路径
                                    String reqeustMethod = array[0];
                                    String reqeustPath = array[1];
                                    Request request = new Request(reqeustMethod,reqeustPath);
                                    Handler handler = new Handler(controllerClass,method);
                                    ACTION_MAP.put(request,handler);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取handler
     * @param requestMethod
     * @param requestPath
     * @return
     */
    public static Handler getHandler(String requestMethod,String requestPath){
        Request request = new Request(requestMethod,requestPath);
        return ACTION_MAP.get(request);
    }
}
